from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from users.models import *
from rest_framework.viewsets import ModelViewSet
from .serializers import *
from mmutils import generate_code, apikey, YunPian
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler
from rest_framework import permissions
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication


from django.contrib.auth import get_user_model
User = get_user_model()


# 自定义用户验证
class CustomBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


# 给手机发验证码
class SmsCodeViewset(ModelViewSet):

    queryset = VerifyCode.objects.all()
    serializer_class = SmsSerializer

    # 重写create方法：（点击发送验证码时，随机生成验证码，把验证码和手机号存到数据库）
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        mobile = serializer.validated_data['mobile']
        code = generate_code(self)
        yunpian = YunPian(apikey)
        sms_status = yunpian.send_sms(code, mobile)

        if sms_status['code'] != 0:
            return Response({'mobile': sms_status['msg']}, status=status.HTTP_400_BAD_REQUEST)
        else:
            record = VerifyCode(code=code, mobile=mobile)
            record.save()
            return Response({'mobile': sms_status['msg']}, status=status.HTTP_201_CREATED)


# 注册视图类
class UserRegViewset(ModelViewSet):

    queryset = UserProfile.objects.all()
    # 用户认证：设置token
    authentication_classes = (SessionAuthentication,
                              JSONWebTokenAuthentication)

    # permission_classes = (permissions.IsAuthenticated, )
    # 动态设置
    def get_permissions(self):
        if self.action == 'retrieve':
            return [permissions.IsAuthenticated()]
        elif self.action == 'create':
            return []
        return []

    # serializer_class = UserRegSerializer
    # 动态获取序列化对象:
    def get_serializer_class(self):
        if self.action == 'retrieve':
            return UserDetailSerializer
        elif self.action == 'create':
            return UserRegSerializer
        return UserDetailSerializer

    # 完成注册后，自动登陆过程
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)

        payload = jwt_payload_handler(user)
        re_dict = serializer.data
        re_dict['token'] = jwt_encode_handler(payload)

        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()

    # 获取用户详情:
    def get_object(self):
        return self.request.user















